﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YmtSystem.CrossCutting;
using YmtSystem.Infrastructure.Config;

namespace YmtAuth.Domain.DomainService
{
    public class AuthClientAppMapping
    {
        private const string defaultMappinName = "_defaultmapp";

        private static readonly Dictionary<string, string> defaultMappingDic = new Dictionary<string, string> 
        {
            {"www.ymatou.com","MainSite"},
            {"www.alpha.ymatou.com","MainSite"},
            {"dev.ymatou.com","MainSite"},
            {"mainsite","MainSite"},
            {"seller.ymatou.com","Seller"},
            {"seller.alpha.ymatou.com","Seller"},
            {"MatouApp","MatouApp"},
            {"App","App"},
            {"m.ymatou.com","Wap"},
            {"m.alpha.ymatou.com","Wap"},
            {"sq.ymatou.com","Sq"},
            {"sq.alpha.ymatou.com","Sq"},
            {"a.ymatou.com","MatouAdmin"},
            {"a.alpha.ymatou.com","MatouAdmin"},
            {"ymatouuserheader","YmatouUserHeader"}
        };

        /// <summary>
        /// 获取客户端映射
        /// </summary>
        /// <param name="clientType">客户端类型（域名或为其分配的应用ID）</param>
        /// <param name="defReturn">默认返回值</param>
        /// <param name="notFindThrowOut">未找到映射是否抛出异常</param>
        /// <param name="description">说明</param>
        /// <returns></returns>
        public static string GetMappinName(string clientType, string defReturn = null, bool notFindThrowOut = false)
        {
            if (clientType.IsEmpty()) return defaultMappinName;
            var file = AppDomain.CurrentDomain.BaseDirectory + "Config\\authmapp.json";
            var dic = file.GetLocalCfgValueByFile(ValueFormart.JSON, defaultMappingDic, TimeSpan.FromHours(24));
            //YmatouLoggingService.Debug("get auth mapping {0} items", dic.Count);

            var result = dic.TryGetV(clientType.ToLower(), null, notFindThrowOut);
            if (!result.IsEmpty())
                return result;

            //YmatouLoggingService.Debug("未找到客户端应用映射 {0},{1}", clientType, description);
            return defReturn.IsEmpty() ? defaultMappinName : defReturn;
        }
        public static void Save(Dictionary<string, string> val)
        {
            var file = AppDomain.CurrentDomain.BaseDirectory + "Config\\authmapp.json";
            var dic = file.GetLocalCfgValueByFile(ValueFormart.JSON, defaultMappingDic, TimeSpan.FromHours(24));

            val.Each(a =>
            {
                dic[a.Key] = a.Value;
            });

            LocalFileCfg.SerializeJSONToStream(dic, file);
        }
    }
}
